// 获取数据
function ran() {
  $.ajax({
    type: 'GET',
    url: '/admin/swipers',
    success: function (res) {
      console.log(res)
      let str = ''
      res.data.forEach(item => {
        let span = '';
        if (item.swiperstatus === 1) {
          span = `<span data-id='${item.id}' data-status='2' class="layui-badge layui-bg-green state">√</span>`
        } else {
          span =  `<span data-id='${item.id}' data-status='1' class="layui-badge layui-bg-cyan state">×</span>`
        }
        str += `
        <tr>
              <td>${item.id}</td>
              <td>
                <img src='http://localhost:8888/uploads/${item.swiperimg}'>
              </td>
              <td>${item.swiperimg}</td>
              <td>${span}</td>
              <td>
                <button data-id="${item.id}" type="button" class="layui-btn layui-btn-xs layui-btn-danger delete">
                  删除
                </button>
              </td>
         </tr>`
      });
      $('tbody').html(str);
    }
  })
}
ran()

// 上传轮播图  自动点击事件触发
$('#uploadSwiper').on('click',function () {
  // console.log(12)
  $('#myfile').trigger('click')
})
// 上传文件
$('#myfile').on('change',function (e) {
  e.preventDefault()
  // console.log(555)
  let files = e.target.files
  let fd = new FormData()
  // 选择图片
  $.each(files, function (index,item) {
     fd.append('swipers', item)   
  })
  // 发送请求，渲染页面
  $.ajax({
    type:'POST',
    url:'/admin/swipers',
    data: fd,
    processData:false,
    contentType:false,
    success: function (res) {
      if (res.status === 0) {
        layer.msg(res.message)
        ran()
      }
    }
  })
})

// 删除功能
$('tbody').on('click','.delete',function () {
  let id = $(this).data('id')
  layer.confirm('您确认删除吗',function (index) {
    $.ajax({
      type:'DELETE',
      url:'/admin/swipers/' + id,
      success: function (res) {
        if (res.status === 0) {
          // 删除成功
          layer.msg(res.message)
          ran()
        }      
      }
    })
  })
})

// 轮播状态切换
$('tbody').on('click','.state',function (e) {
  // console.log(11111)
  e.preventDefault()
  let status = $(this).data('status')
  let id = $(this).data('id')
  $.ajax({
    type:'PUT',
    url:'/admin/swipers/'+id,
    data: {
      status:status
    },
    success:function (res) {
      if (res.status === 0 ) {
        layer.msg(res.message)
        ran()
      }      
    }
  })
})